package com.micromall.common.utils;

import org.apache.poi.ss.formula.functions.T;

import java.beans.BeanInfo;
import java.beans.Introspector;  
import java.beans.PropertyDescriptor;  
import java.lang.reflect.Method;  
  
public class BeanInfoUtil {  
      
    // 通过内省设置bean的某个属性值  
    public static void setPropertyByIntrospector(Class<T> clazz,T t,String value) throws Exception {
        // 获取bean信息  
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
        // 获取bean的所有属性列表  
        PropertyDescriptor[] proDescrtptors = beanInfo.getPropertyDescriptors();  
        // 遍历属性列表，查找指定的属性  
        if (proDescrtptors != null && proDescrtptors.length > 0) {  
            for (PropertyDescriptor propDesc : proDescrtptors) {  
                // 找到则写入属性值  
                Method methodSetUserName = propDesc.getWriteMethod();
                methodSetUserName.invoke(t, value);  // 写入属性值
                break;
            }
        }  
    }  
  
    // 通过内省获取bean的某个属性值  
    public static void getPropertyByIntrospector(Class<T> clazz,T t,String fieldName) throws Exception {
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
        PropertyDescriptor[] proDescrtptors = beanInfo.getPropertyDescriptors();  
        if (proDescrtptors != null && proDescrtptors.length > 0) {  
            for (PropertyDescriptor propDesc : proDescrtptors) {  
                if (propDesc.getName().equals(fieldName)) {
                    Method methodGetUserName = propDesc.getReadMethod();  
                    Object objUserName = methodGetUserName.invoke(t);
                    break;
                }  
            }  
        }  
    }  
}  